import {
  getWorkOrderList,
  getProjectName,
  exportWorkOrderInfo,
  ossDownload
} from '/service/service'

import {
  getContainerHeight
} from '/utils/getDimensionUtil'
const {
  getCurrentStatusMap
} = require('/utils/statusMap')
Page({
  data: {
    searchValue: null,
    searchHeight: 0,
    autoRefreshInterval: 0,
    pagePath: '',
    currentIntervalStatus: false,

    pageNum: 1,
    pageSize: 10,
    total: 0,
    currentTotal: 0,
    list: [],
    hasMore: true,
    windowHeight: 0,
    isLoading: false,
    scrollTop: 0,
    scrollViewHeight: 0,
    showBackTop: false,
    loadLock: false, // 新增加载锁

    rangeKey: 0,
    fixRange: ['', ''],
    statusOptions: ['请选择当前状态', '待派遣', '待接单', '处理中', '运维单位处理时回退至派遣', '初审', '终审', '结案', '处理中(已延期)', '作废', '待接单(派遣)', '待接单(转派)', '待接单(预审)', '待接单(初审)', '待接单(终审)', '预审'],
    statusOptionsIndex: 0,
    projectNameList: [],
    projectNameListIndex: 0,
    projectId: '',
    searchContent: {}
  },
  onLoad() {
    this.initPagePathAndAutoRefresh()
    this.getProjectNameList()
    this.getWindowHeight()
    this.getList()
  },
  onPullDownRefresh() {
    console.log('下拉刷新');
    this.setData({
      pageNum: 1,
      list: [],
      hasMore: true,
      loadLock: false // 重置加载锁
    }, async () => {
      try {
        await this.getList();
      } catch (e) {
        console.error('下拉刷新失败：', e);
      } finally {
        dd.stopPullDownRefresh();
      }
    });
  },
  initPagePathAndAutoRefresh() {
    try {
      // 1.取当前页面路径
      const currentPage = getCurrentPages().at(-1);
      const pagePath = currentPage.route || '';
      this.setData({
        pagePath
      });
      console.log(pagePath)
      // 2. 读取本地存储
      const autoRefreshInterval = my.getStorageSync({
        key: pagePath
      }).data
      // 3. 校验并设置自动刷新间隔
      if (autoRefreshInterval) {
        this.setData({
          autoRefreshInterval
        }, () => {
          console.log('当前页面自动刷新间隔初始化成功：', this.data.autoRefreshInterval);
        });
      } else {
        console.log('自动刷新配置无效，不初始化：', {
          autoRefreshInterval
        });
      }
    } catch (err) {
      console.error('初始化页面路径与自动刷新失败：', err);
    }
  },
  onPageScroll(e) {
    const {
      scrollTop
    } = e
    const {
      windowHeight,
      scrollViewHeight,
      isLoading,
      hasMore,
      loadLock,
      total,
      list
    } = this.data
    
    this.setData({
      showBackTop: scrollTop > 300
    });
    
    // 基本条件判断：如果正在加载、没有更多数据、有加载锁或总数据为0，则不触发
    if (isLoading || !hasMore || loadLock || total === 0) return
    
    // 剩余高度 = 列表总高度 - 滚动距离 - 窗口高度
    const remainingDistance = scrollViewHeight - scrollTop - windowHeight
    // console.log(`剩余距离: ${remainingDistance}, 列表长度: ${list.length}, 总条数: ${total}`)
    
    if (remainingDistance < 20 && list.length < total) {
      this.setData({ loadLock: true }) // 锁定加载
      
      this.setData({
        pageNum: this.data.pageNum + 1
      }, () => {
        // 确保getList完成后再解锁
        this.getList().finally(() => {
          this.setData({ loadLock: false })
        })
      })
    }
    
    this.setData({
      scrollTop
    })
  },
  onReady() {
    this.getSearchHeight()
    this.getWrapHeight()
  },
  onShow() {
    this.handleSearch()
  },
  onHide() {
    const {
      currentIntervalStatus
    } = this.data
  },
  getProjectNameList() {
    getProjectName().then(res => {
      const nameList = []
      res.forEach(item => {
        if (item && item.projectName)
          nameList.push(item.projectName)
      })
      nameList.unshift('请选择项目')
      this.setData({
        projectNameList: nameList
      });
    }).catch(e => {
      console.error(`获取项目名称列表失败：${e}`)
    })
  },
  getWindowHeight() {
    const systemInfo = my.getSystemInfoSync()
    this.setData({
      windowHeight: systemInfo.windowHeight
    })
  },
  async getList() {
    if (this.data.isLoading || !this.data.hasMore) return
    const {
      pageNum,
      pageSize,
      searchContent
    } = this.data
    const params = {
      pageNum,
      pageSize,
      ...searchContent
    }
    try {
      this.setData({
        isLoading: true
      })
      const res = await getWorkOrderList(params)
      const {
        rows,
        total
      } = res || { rows: [], total: 0 }
      
      const filteredRows = rows.filter(r =>
        !this.data.list.some(old => old.id === r.id)
      );

      const newList = [];
      for (const item of filteredRows) {
        const attachmentToParse = JSON.parse(item.attachment)
        let preImgPath = null
        if (attachmentToParse && attachmentToParse.length > 0) {
          const preImg = attachmentToParse[0]
          preImgPath = await ossDownload(preImg.ossId)
        }
        newList.push({
          ...item,
          currentStatusName: getCurrentStatusMap(item.status),
          imgs: JSON.parse(item.attachment),
          preImgPath
        });
      }
      
      const updateList = this.data.list.concat(newList)
      // 调整hasMore判断逻辑：只要当前列表长度小于总条数，就认为还有更多
      const hasMore = updateList.length < total
      
      console.log(`加载第${pageNum}页，新增${newList.length}条，总${updateList.length}/${total}，是否还有更多: ${hasMore}`)
      
      this.setData({
        list: updateList,
        total,
        hasMore,
        isLoading: false
      }, () => {
        this.getWrapHeight()
      })
    } catch (e) {
      this.setData({
        isLoading: false,
        loadLock: false // 出错时释放加载锁
      })
      my.alert({
        content: '加载失败，请重试'
      })
      console.error('加载失败:', e)
    }
  },

  async getSearchHeight() {
    const [h1, h2] = await Promise.all([
      getContainerHeight('.search-line-container'),
      getContainerHeight('.refreshControl_container')
    ]);
    const total = h1 + h2;
    if (total) {
      this.setData({
        searchHeight: total
      })
    }
  },
  async getWrapHeight() {
    const scrollViewHeight = await getContainerHeight('.workOrderQuery_container')
    if (scrollViewHeight) {
      this.setData({
        scrollViewHeight
      })
    }
  },
  viewDetail(e) {
    my.navigateTo({
      url: `/pages/detail/detail?id=${e}`
    })
  },
  backToTop() {
    my.pageScrollTo({
      scrollTop: 0,
      duration: 300
    });
    this.setData({
      showBackTop: false
    });
  },
  searchInput(e) {
    this.setData({
      projectId: e.detail.value,
      'searchContent.id': e.detail.value
    })
  },
  handleSearch(val) {
    console.log(val)
    const typeOfVal = typeof val
    console.log(`val类型：${typeOfVal}`)
    if (val === null || typeOfVal === 'string') {
      this.setData({
        searchValue: val
      })
    } else {
      console.log('等于真object')
    }
    const {
      searchValue
    } = this.data

    const searchContent = {
      faultLocation: searchValue
    };

    this.setData({
      list: [],
      searchContent,
      pageNum: 1,
      pageSize: 10,
      hasMore: true,
      isLoading: false,
      loadLock: false // 重置加载锁
    }, () => {
      this.getList().then(() => {
        // this.backToTop()
      })
    });
  },
  onIntervalChange(e) {
    console.log(e)
    const {
      enabled,
      interval
    } = e;
    const {
      pagePath
    } = this.data
    my.setStorageSync({
      key: pagePath,
      data: interval
    })
    const {
      currentIntervalStatus
    } = this.data
    if (enabled !== currentIntervalStatus) {
      this.setData({
        currentIntervalStatus: enabled
      })
    }
    this.getSearchHeight()
    console.log(`自动刷新${enabled ? '开启' : '关闭'}，间隔${interval}秒`)
  },
  handleReset(e) {
    console.log(e)
    this.setData({
      rangeKey: this.data.rangeKey + 1,
      fixRange: ['', ''],
      statusOptionsIndex: 0,
      projectId: '',
      projectNameListIndex: 0,
      searchContent: {},
      list: [],
      pageNum: 1,
      pageSize: 10,
      hasMore: true,
      isLoading: false,
      loadLock: false // 重置加载锁
    }, () => {
      this.getList().then(() => {
        this.backToTop()
      });
    });
  },

  onProjectNameChange(e) {
    this.setData({
      projectNameListIndex: e.detail.value,
      'searchContent.projectName': e.detail.value > 0 ? this.data.projectNameList[e.detail.value] : null
    });
  },
  onStatusChange(e) {
    this.setData({
      statusOptionsIndex: e.detail.value,
      'searchContent.status': e.detail.value > 0 ? e.detail.value - 1 : null
    });
  },
  handleRangeOk(date, format, e) {
    console.log(format)
    this.setData({
      fixRange: format,
      'searchContent.fixRange': format
    })
  },
  formExport() {
    console.log('点击导出工单')
    const {
      id
    } = this.data.searchContent
    console.log(id)
    exportWorkOrderInfo({
      id
    }, `工单导出${id}`).then(res => {
      console.log(res.data)
    })
  }
});
    